using System;
using System.Web.Mvc;
using RestUpMVC.BlogService.Resources;
using System.Linq;

namespace RestUpMVC.BlogService.Controllers
{
    public class BlogController : Controller
    {
        public ActionResult List(int? start, int? limit)
        {
            if (!start.HasValue)
            {
                start = 0;
            }
            if (!limit.HasValue)
            {
                limit = 25;
            }
            return this.RestOk(Domain.Blog.Get().Select(x=>new Blog(){Description = x.Description, Id = x.Id, Name = x.Name}).ToArray());
        }

        public ActionResult Get(Guid id)
        {
            var blog = Domain.Blog.Get(id);
            return blog == null ? this.RestNotFound(new {Message = "The resource was not found."}) : this.RestOk(blog);
        }

        public ActionResult Post(Blog blog)
        {
            var newBlog = new Domain.Blog {Description = blog.Description, Name = blog.Name};
            Domain.Blog.Create(ref newBlog);
            blog.Id = newBlog.Id;
            return this.RestCreated(blog);
        }

        public ActionResult Put(Guid id, Blog blog  )
        {
            var domain = Domain.Blog.Get(id);
            if (null == domain)
            {
                return this.RestNotFound(new {Message = "The resource was not found."});
            }
            domain.Description = blog.Description;
            domain.Name = blog.Name;
            domain.Save();
            return this.RestOk(blog);
        }

        public ActionResult Delete(Guid id)
        {
            var blog = Domain.Blog.Get(id);
            if (null == blog)
            {
                return this.RestNotFound(new { Message = "The resource was not found." });
            }
            Domain.Blog.Delete(blog);
            return this.RestNoContent();
        }
    }
}